package net.sf.log4jdbc;

public class PatterUtil {

    public static boolean compare(String pattern, String str) {
        pattern = toJavaPattern(pattern);
        return java.util.regex.Pattern.matches(pattern, str);
    }

    private static String toJavaPattern(String pattern) {
        // String result = "^";
        StringBuffer result = new StringBuffer("^");
        char metachar[] = { '$', '^', '[', ']', '(', ')', '{', '|', '+', '.', '/', '\\' };
        for (int i = 0; i < pattern.length(); i++) {
            char ch = pattern.charAt(i);
            boolean isMeta = false;
            for (int j = 0; j < metachar.length; j++) {
                if (ch == metachar[j]) {
                    // result += "\\" + ch;
                    result.append("\\" + ch);
                    isMeta = true;
                    break;
                }
            }

            if (!isMeta) {
                if (ch == '*') {
                    // result += ".*";
                    result.append(".*");
                } else if (ch == '?') {
                    // result += '.';
                    result.append('.');
                } else {
                    // result += ch;
                    result.append(ch);
                }
            }
        }
        // result += "$";
        result.append("$");
        return result.toString();
    }

    public static boolean classMatch(String className, String pkgFlag) {
        int tmp = 0;
        String[] pkgs = System.getProperty(pkgFlag).split(";");
        if (pkgs.length == 0)
            return false;
        for (String pkg : pkgs) {
            String str = "";
            if (pkg != null && !("").equals(pkg)) {
                if (pkg.endsWith("*")) {
                    str = pkg;
                } else {
                    str = pkg + "*";
                }
                if (str.startsWith("!") && PatterUtil.compare(str.substring(1), className)) {
                    return false;
                } else if (PatterUtil.compare(str, className)) {
                    tmp++;
                }
            }
        }
        return tmp > 0;
    }

    public static void main(String[] args) {
        test("!com.aaa.bdf.*.tx.*tor*", "com.aaa.bdf.rbpm.pvm.internal.tx.SpringTransactionInterceptor");
    }

    private static void test(String pattern, String str) {
        System.out.println(pattern + ", " + str + " =>> " + compare(pattern, str));
    }
}
